<?php

namespace app\admin\controller\fastim;

use think\Db;
use app\common\controller\Backend;
use addons\fastim\library\Common;

/**
 * 群聊管理
 *
 * @icon fa fa-circle-o
 */
class Groupchat extends Backend
{

    /**
     * Groupchat模型对象
     * @var \app\admin\model\fastim\Groupchat
     */
    protected $model = null;

    protected $pageCount = 15;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fastim\Groupchat;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("addModeList", $this->model->getAddModeList());
        $this->view->assign("inviteJoinGroupList", $this->model->getInviteJoinGroupList());
        $this->view->assign("speakList", $this->model->getSpeakList());
        $this->view->assign("historyMessageList", $this->model->getHistoryMessageList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 当前用户列表
     */
    public function users($ids, $page = 1)
    {
        $groupMember = Db::name('fastim_group_user')
            ->alias('gu')
            ->field('gu.nickname,gu.speaktime,gu.jointime,u.id,u.avatar,u.nickname as u_nickname,u.status,fu.avatar as fu_avatar,fu.nickname as fu_nickname,a.avatar as a_avatar,a.nickname as a_nickname,f.remark,f.user_id as is_friend')
            ->join('fastim_user u', 'u.id=gu.user_id')
            ->join('user fu', 'fu.id=u.user_id', 'LEFT')
            ->join('admin a', 'a.id=u.admin_id', 'LEFT')
            ->join('fastim_friendship f', 'f.friend_id=u.id AND f.user_id=:user_id', 'LEFT')
            ->bind([
                'user_id' => $ids
            ]);

        $groupMember = $groupMember->where('gu.group_id', $ids)->order('gu.jointime desc')->select();

        foreach ($groupMember as $key => $value) {
            // 原始昵称
            $groupMember[$key]['nickname_origin'] = Common::trueAttr(Common::nicknameSort([
                $value['remark'],
                $value['u_nickname'],
                $value['fu_nickname'],
                $value['a_nickname']
            ], $value['id']));

            $groupMember[$key]['avatar'] = Common::avatarSrc([
                $value['avatar'],
                $value['fu_avatar'],
                $value['a_avatar']
            ], $groupMember[$key]['nickname_origin']);

            $groupMember[$key]['speaktime'] = Common::formatTime($value['speaktime'] ? $value['speaktime'] : $value['jointime']);
            unset($groupMember[$key]['remark'], $groupMember[$key]['u_nickname'], $groupMember[$key]['fu_nickname'], $groupMember[$key]['a_nickname'], $groupMember[$key]['fu_avatar'], $groupMember[$key]['a_avatar']);
        }

        $this->assign('group_member', $groupMember);

        return $this->view->fetch();
    }

    /**
     * 聊天记录
     */
    public function record($ids, $page = 1)
    {
        $groupChatInfo = Common::getImGroupChat($ids);
        $imSession     = Common::imSession('group', $groupChatInfo['leader'], $groupChatInfo['id']);
        $sessionInfo   = Common::sessionInfo($imSession['id'], $groupChatInfo['leader']);

        if (!$sessionInfo) {
            $this->error(__('No Results were found'));
        }

        if ($page == 1) {
            $min = 0;
        } else {
            $min = ($page - 1) * $this->pageCount;
        }

        if ($sessionInfo['type'] == 'group') {

            $message = Common::loadGroupChatRecord($sessionInfo, [
                'min'       => $min,
                'pageCount' => $this->pageCount
            ], $sessionInfo['user_one']);

            $sessionInfo['windowType'] = 'message';
        } else {
            $this->error('加载失败，请重试！');
        }

        $nextpage = (count($message) < $this->pageCount) ? false : true;
        $message  = Common::groupByTime($message);

        if ($this->request->isAjax()) {
            $this->success('ok', '', [
                'pageData'    => [
                    'nextpage' => $nextpage,
                    'page'     => $page
                ],
                'message'     => $message,
                'sessionInfo' => $sessionInfo
            ]);
        }

        $this->assignconfig('pageData', [
            'nextpage' => $nextpage,
            'page'     => $page,
            '__CDN__'  => $this->request->domain()
        ]);
        $this->assignconfig('message', $message);
        $this->assignconfig('sessionInfo', $sessionInfo);
        return $this->view->fetch();
    }

    /**
     * 回收站
     *
     * @return string|Json
     * @throws \think\Exception
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->with(['fastimuser' => ['fauser', 'admin']])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {

            $row->getRelation('fastimuser')->visible(['nickname']);
            $aNickname  = $row->fastimuser->admin->nickname ?? '';
            $faNickname = $row->fastimuser->fauser->nickname ?? '';
            if ($aNickname || $faNickname) {
                $row->fastimuser->nickname = $row->fastimuser->nickname . '(' . ($aNickname ? $aNickname : $faNickname) . ')';
            }
            //当前人数
            $row->user_count = Db::name('fastim_group_user')->where('group_id', $row->id)->count('user_id');
        }
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['fastimuser' => ['fauser', 'admin']])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('fastimuser')->visible(['nickname']);
                $aNickname  = $row->fastimuser->admin->nickname ?? '';
                $faNickname = $row->fastimuser->fauser->nickname ?? '';
                if ($aNickname || $faNickname) {
                    $row->fastimuser->nickname = $row->fastimuser->nickname . '(' . ($aNickname ? $aNickname : $faNickname) . ')';
                }
                //当前人数
                $row->user_count = Db::name('fastim_group_user')->where('group_id', $row->id)->count('user_id');
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

}
